<template>
  <el-row id="globalHeader" :gutter="0">
    <!-- logo -->
    <el-col id="globalHeaderLogo" :span="2" :offset="0">
      <img class="logo" src="../assets/logo.jpg" />
    </el-col>

    <!-- 菜单栏: 默认激活项跟随路由变化 -->
    <el-col :span="18" :offset="0">
      <el-menu id="globalHeaderMenu" mode="horizontal" :default-active="router.currentRoute.value.path" router
        class="el-menu-demo" @select="doMenuClick">
        <el-menu-item v-for="item in visibleRoutes" :index="item.path">{{ item.name }}</el-menu-item>
      </el-menu>
    </el-col>

    <!-- 右侧登录 -->
    <el-col id="globalHeaderUser" :span="4" :offset="0">
      <div class="globalHeaderUserWrapper">
        <!-- 未登录, 则显示登录按钮 -->
        <el-button type="primary" v-if="loginUserStore.loginUser.userRole === UserRoleEnum.NOT_LOGIN"
          @click="router.push({ name: '用户登录' })">
          登录
        </el-button>
        <!-- 已登录, 则显示用户信息 -->
        <el-dropdown v-else placement="bottom-end" trigger="click">
          <div class="userInfoWrapper">
            <div class="userName">{{ loginUserStore.loginUser.userName }}</div>
            <el-avatar size="large" shape="circle" style="cursor: pointer;" :src="loginUserStore.loginUser.userAvatar"
              fit="fill" />
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="prepareMyInfoDialog">更新个人信息</el-dropdown-item>
              <el-dropdown-item @click="doLogout"><span style="color: red;">退出登录</span></el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-col>
  </el-row>

  <el-dialog title="更新个人信息" v-model="myInfoDialogVisible" width="30%">
    <el-form :model="myInfoForm" label-width="80px">
      <el-form-item label="用户昵称">
        <el-input v-model="myInfoForm.userName" />
      </el-form-item>
      <el-form-item label="用户头像">
        <PictureUploader v-model:image-url="myInfoForm.userAvatar" :file-upload-type="FileUploadTypeEnum.USER_AVATAR" />
      </el-form-item>
      <el-form-item label="用户简介">
        <el-input v-model="myInfoForm.userProfile" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span>
        <el-button @click="myInfoDialogVisible = false">返回</el-button>
        <el-button type="primary" @click="doUpdateMyInfo">提交更新</el-button>
      </span>
    </template>
  </el-dialog>

</template>

<script setup lang="ts">
import routes from "@/router/routes";
import { useRouter } from "vue-router";
import { computed, onMounted, reactive, ref, toRef, toRefs } from "vue";
import { useLoginUserStore } from "@/stores/userStore";
import { FileUploadTypeEnum, ResponseCodeEnum, UserRoleEnum } from "@/enums";
import authCheck from "@/access/authCheck";
import { ElMessage, ElMessageBox } from "element-plus";
import { updateMyInfoUsingPost } from "@/api/userController";
import PictureUploader from "./PictureUploader.vue";

const router = useRouter();
const loginUserStore = useLoginUserStore();

// 过滤并展示应当出现在菜单栏的路由
const visibleRoutes = computed(() => {
  return routes.filter((item) => {
    // 判断页面是否在菜单栏中隐藏
    if (item.meta?.hideInMenu) {
      return false;
    }

    // 根据权限过滤菜单
    if (!authCheck(loginUserStore.loginUser, item.meta?.access as UserRoleEnum)) {
      return false;
    }

    return true;
  });
});

/**
 * 点击菜单跳转到对应页面
 * @param key 
 * @param keyPath 
 */
const doMenuClick = (key: string, keyPath: string[]) => {
  // defaultActiveIndex.value = key
  router.push(key);
};

/**
 * 退出登录
 */
const doLogout = () => {
  ElMessageBox.confirm(
    '确定要退出嘛 ?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    await loginUserStore.logout();
    ElMessage.success("已成功退出登录");
  }).then(() => {
    // 返回首页
    router.push("/")
  }).catch(() => { })
};

// 首次挂载时, 获取当前登录用户
onMounted(async () => {
  await loginUserStore.fetchLoginUser();
});

/**
 * 准备更新个人信息 dialog
 */
const prepareMyInfoDialog = () => {
  // 获取当前登录用户信息
  Object.assign(myInfoForm.value, loginUserStore.loginUser)

  myInfoDialogVisible.value = true;
};


// 更新个人信息 dialog 是否可见
const myInfoDialogVisible = ref(false);

// 更新个人信息表单 (为了解构属性传给模块, 改用 reactive)
const myInfoForm = ref<API.UserUpdateMyInfoRequest>({
  userName: '',
  userAvatar: '',
  userProfile: '',
})

/**
 * 提交个人信息更新
 */
const doUpdateMyInfo = async () => {
  // 更新用户信息
  const result = await updateMyInfoUsingPost(myInfoForm.value);
  
  if (result.data.code === ResponseCodeEnum.SUCCESS) {
    ElMessage.success("更新个人信息成功");
    // 重新获取当前登录用户信息
    loginUserStore.fetchLoginUser();
    myInfoDialogVisible.value = false;
  } else {
    ElMessage.error("更新失败: " + result.data.message);
  }
}


</script>

<style scoped lang="less">
#globalHeaderLogo {
  display: flex;
  align-items: center;
  justify-content: center;
  border-bottom: 1px solid rgb(220, 223, 230);
  height: 8vh;

  img {
    max-height: 6vh;
    max-width: 90%;
  }
}

#globalHeaderMenu {
  height: 8vh;
}

#globalHeaderUser {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-bottom: 1px solid rgb(220, 223, 230);
  height: 8vh;
  position: relative;

  .globalHeaderUserWrapper {
    right: 15px;
    position: absolute;

    .userInfoWrapper {
      display: flex;
      align-items: center;
      justify-content: center;

      .el-avatar {
        height: 6vh;
        width: 6vh;
      }

      .userName {
        font-size: 1.4em;
        margin-right: 10px;
      }
    }
  }
}

.title {
  margin-left: 16px;
  color: black;
}
</style>
